﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SportsPlatform.PermissionManagement.IPermissionManagement;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Query.PermissionManagement.CompanyInfo;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Query.PermissionManagement.BaseQuery;
using SportsPlatform.Dto.PermissionManagement.CompanyInfo;
using Abp.Domain.Repositories;
using Abp.Collections.Extensions;
using Abp.Application.Services;
using Microsoft.AspNetCore.Http;
using SportsPlatform.Global;

namespace SportsPlatform.PermissionManagement.PermissionManagement
{
    /// <summary>
    /// 公司表
    /// </summary>
    [RemoteService(false)]  //隐藏自动生成的WebApi
    public class CompanyInfoService : SportsPlatformAppServiceBase, ICompanyInfoService
    {
        private readonly IRepository<CompanyInfo, Guid> _companyinfoRepository;

        private readonly IRepository<CompanyTypeInfo, Guid> _companytypeinfoRepository;

        private readonly IRepository<UserInfo, Guid> _userinfoRepository;

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="companyinfoRepository"></param>
        /// <param name="userinfoRepository"></param>
        /// <param name="companytypeinfoRepository"></param>
        /// <param name="context"></param>
        public CompanyInfoService(IRepository<CompanyInfo, Guid> companyinfoRepository, IRepository<UserInfo, Guid> userinfoRepository,
            IRepository<CompanyTypeInfo, Guid> companytypeinfoRepository, IHttpContextAccessor context) : base(context)
        {
            _companyinfoRepository = companyinfoRepository;
            _userinfoRepository = userinfoRepository;
            _companytypeinfoRepository = companytypeinfoRepository;
        }

        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="addCompanyInfoQuery"></param>
        /// <returns></returns>
        public async Task<ResultDto<AddCompanyInfoDto>> AddCompanyInfo(AddCompanyInfoQuery addCompanyInfoQuery)
        {
            ResultDto<AddCompanyInfoDto> resultDto = new ResultDto<AddCompanyInfoDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                if ((await _userinfoRepository.FirstOrDefaultAsync(info => info.Id == addCompanyInfoQuery.ContactsUserId && info.IsDeleted == false && info.States == true)) == null)
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "未查询到所属人信息！";
                    return resultDto;
                }
                CompanyInfo companyInfo = ObjectMapper.Map<CompanyInfo>(addCompanyInfoQuery);
                companyInfo.AuthorizeStates = 1;
                companyInfo.Create(this._context);
                companyInfo.CreateUserId = token.Id;
                var companyid = await _companyinfoRepository.InsertAndGetIdAsync(companyInfo);
                resultDto.IsSuccess = true;
                resultDto.Code = HttpResultCode.Success;
                resultDto.Message = "新增成功！";
                resultDto.Data = new AddCompanyInfoDto() { Id = companyid };
            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 根据Id删除信息
        /// </summary>
        /// <param name="deleteOrQueryModel"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> DeleteCompanyInfo(DeleteOrGetModelQuery deleteOrQueryModel)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                var companyInfo = await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == deleteOrQueryModel.Id);
                if (companyInfo != null)
                {
                    companyInfo.Delete(this._context);
                    companyInfo.DeleteUserId = token.Id;
                    await _companyinfoRepository.UpdateAsync(companyInfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "删除成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.Fail;
                    baseResultDto.Message = "未查询到该Id信息！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 根据Id获取信息
        /// </summary>
        /// <param name="deleteOrQueryModel"></param>
        /// <returns></returns>
        public async Task<ResultDto<GetCompanyInfoDto>> GetCompanyInfo(DeleteOrGetModelQuery deleteOrQueryModel)
        {
            ResultDto<GetCompanyInfoDto> resultDto = new ResultDto<GetCompanyInfoDto>();
            try
            {
                var companyInfo = await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == deleteOrQueryModel.Id);
                if (companyInfo != null)
                {
                    resultDto.IsSuccess = true;
                    resultDto.Code = HttpResultCode.Success;
                    resultDto.Message = "查询成功！";
                    GetCompanyInfoDto infoDto = ObjectMapper.Map<GetCompanyInfoDto>(companyInfo);
                    var userinfo = _userinfoRepository.FirstOrDefault(info => info.Id == companyInfo.ContactsUserId);
                    infoDto.ContactsUserName = userinfo.UserName;
                    infoDto.ContactsUserTel = userinfo.UserTel;
                    infoDto.ContactsUserLoginName = userinfo.LoginName;
                    infoDto.ContactsUserIdNo = userinfo.UserIdNo;
                    infoDto.ContactsUserIdNoPhoto = userinfo.UserIdNoPhoto;
                    infoDto.CompanyTypeName = _companytypeinfoRepository.FirstOrDefault(info => info.Id == companyInfo.CompanyTypeId).CompanyTypeName;
                    resultDto.Data = infoDto;
                }
                else
                {
                    resultDto.IsSuccess = false;
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.Message = "未查询到该Id信息！";
                }

            }
            catch (Exception e)
            {
                resultDto.IsSuccess = false;
                resultDto.Code = HttpResultCode.Error;
                resultDto.Message = e.Message.ToString();
            }
            return resultDto;
        }

        /// <summary>
        /// 续期
        /// </summary>
        /// <param name="companyRenewalQuery"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> CompanyRenewal(CompanyRenewalQuery companyRenewalQuery)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var companyinfo = await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == companyRenewalQuery.Id);
                if (companyinfo != null)
                {
                    //如果已经过期，更改起始时间
                    if (companyinfo.AuthorizeEndTIme < DateTime.Now)
                    {
                        companyinfo.AuthorizeBeginTime = DateTime.Now.Date;
                    }
                    companyinfo.UsageTime = Math.Abs(((TimeSpan)(companyRenewalQuery.AuthorizeEndTIme - companyinfo.AuthorizeBeginTime)).Days).ToString() + "天";
                    companyinfo.AuthorizeEndTIme = companyRenewalQuery.AuthorizeEndTIme;
                    await _companyinfoRepository.UpdateAsync(companyinfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "续期成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.SqlError;
                    baseResultDto.Message = "未查询到相关Id信息！";
                }
            }
            catch (Exception ex)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = ex.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 分页获取客户信息
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetCompanyInfoListPageDto>> GetCompanyInfoListPage(GetCompanyInfoListPageQuery query)
        {
            PagePagingDto<GetCompanyInfoListPageDto> pagePagingDto = new PagePagingDto<GetCompanyInfoListPageDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                var companyinfolist = (await _companyinfoRepository.GetAllListAsync())
                        .WhereIf(!string.IsNullOrEmpty(query.CompanyName), info => info.CompanyName.Contains(query.CompanyName))
                        .WhereIf(query.CompanyTypeId != null && query.CompanyTypeId.Count() > 0, info => query.CompanyTypeId.ToList().Exists(id => id.Equals(info.CompanyTypeId.ToString())))
                        .WhereIf(token.CompanyId != null, info => info.Id == token.CompanyId)
                        .OrderByDescending(info => info.CreateTime)
                        .ToList();
                var companyinfopage = companyinfolist.Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize).ToList();

                if (companyinfopage != null && companyinfopage.Count > 0)
                {
                    var companytypelist = await _companytypeinfoRepository.GetAllListAsync();
                    var userinfolist = await _userinfoRepository.GetAllListAsync();
                    var list = new List<GetCompanyInfoListPageDto>();
                    foreach (var item in companyinfopage)
                    {
                        var dto = new GetCompanyInfoListPageDto();
                        dto.Id = item.Id;
                        dto.States = item.States;
                        dto.CreateTime = item.CreateTime.ToString("yyyy-MM-dd HH:mm:ss");
                        dto.UsageTime = item.UsageTime;
                        var ContactsUserInfo = userinfolist.Where(info => info.Id == item.ContactsUserId).FirstOrDefault();
                        dto.ContactsUserName = ContactsUserInfo.UserName;
                        dto.ContactsUserLoginName = ContactsUserInfo.LoginName;
                        dto.ContactsUserTel = ContactsUserInfo.UserTel.Substring(0, 3) + "****" + ContactsUserInfo.UserTel.Substring(ContactsUserInfo.UserTel.Length - 4, 4);
                        dto.CompanyTypeName = companytypelist.Where(info => info.Id == item.CompanyTypeId).FirstOrDefault()?.CompanyTypeName;
                        dto.CreateUserName = userinfolist.Where(info => info.Id == item.CreateUserId).FirstOrDefault()?.UserName;
                        dto.ClientAuthorizationCodeNumber = item.ClientAuthorizationCodeNumber;
                        dto.CompanyAddress = item.CompanyAddress;
                        dto.CompanyName = item.CompanyName;
                        dto.CompanyAlias = item.CompanyAlias;
                        dto.DaysRemaining = item.AuthorizeEndTIme < DateTime.Now ? "0天" : Math.Abs(((TimeSpan)(item.AuthorizeEndTIme - DateTime.Now)).Days).ToString() + "天";
                        dto.AuthorizeEndTIme = item.AuthorizeEndTIme.ToString("yyyy-MM-dd");
                        list.Add(dto);
                    }

                    pagePagingDto.Data = list;
                    pagePagingDto.IsSuccess = true;
                    pagePagingDto.Code = HttpResultCode.Success;
                    pagePagingDto.Message = "查询成功！";
                    pagePagingDto.TotalCount = companyinfolist.Count;
                    pagePagingDto.TotalPage = companyinfolist.Count % query.PageSize == 0 ? companyinfolist.Count / query.PageSize : companyinfolist.Count / query.PageSize + 1;
                }
                else
                {
                    pagePagingDto.IsSuccess = false;
                    pagePagingDto.Code = HttpResultCode.NotData;
                    pagePagingDto.Message = "未查询到信息";
                }
            }
            catch (Exception ex)
            {
                pagePagingDto.IsSuccess = false;
                pagePagingDto.Code = HttpResultCode.Error;
                pagePagingDto.Message = ex.Message.ToString();
            }
            return pagePagingDto;
        }

        /// <summary>
        /// 是否启用
        /// </summary>
        /// <param name="isStatesModel"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> IsStatesCompanyInfo(IsStatesdModel isStatesModel)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                var companyInfo = await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == isStatesModel.Id);
                if (companyInfo != null)
                {
                    companyInfo.States = isStatesModel.States;
                    companyInfo.UpdateTime = DateTime.Now;
                    companyInfo.UpdateUserId = token.Id;
                    await _companyinfoRepository.UpdateAsync(companyInfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更改成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.SqlError;
                    baseResultDto.Message = "未查询到相关Id信息！";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 更新信息
        /// </summary>
        /// <param name="updateCompanyInfoQuery"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateCompanyInfo(UpdateCompanyInfoQuery updateCompanyInfoQuery)
        {
            BaseResultDto baseResultDto = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);

                var companyinfo = await _companyinfoRepository.FirstOrDefaultAsync(info => info.Id == updateCompanyInfoQuery.Id);
                if (companyinfo != null)
                {
                    companyinfo.UpdateTime = DateTime.Now;
                    companyinfo.UpdateUserId = token.Id;
                    if (updateCompanyInfoQuery.States != null)
                    {
                        companyinfo.States = (bool)updateCompanyInfoQuery.States;
                    }
                    if (!string.IsNullOrEmpty(updateCompanyInfoQuery.CompanyName))
                    {
                        companyinfo.CompanyName = updateCompanyInfoQuery.CompanyName;
                    }
                    if (!string.IsNullOrEmpty(updateCompanyInfoQuery.CompanyAlias))
                    {
                        companyinfo.CompanyAlias = updateCompanyInfoQuery.CompanyAlias;
                    }
                    if (!string.IsNullOrEmpty(updateCompanyInfoQuery.CompanyDescribe))
                    {
                        companyinfo.CompanyDescribe = updateCompanyInfoQuery.CompanyDescribe;
                    }
                    if (!string.IsNullOrEmpty(updateCompanyInfoQuery.CompanyLogo))
                    {
                        companyinfo.CompanyLogo = updateCompanyInfoQuery.CompanyLogo;
                    }
                    if (!string.IsNullOrEmpty(updateCompanyInfoQuery.CompanyAddress))
                    {
                        companyinfo.CompanyAddress = updateCompanyInfoQuery.CompanyAddress;
                    }
                    if (updateCompanyInfoQuery.CompanyTypeId != null)
                    {
                        companyinfo.CompanyTypeId = (Guid)updateCompanyInfoQuery.CompanyTypeId;
                    }
                    if (updateCompanyInfoQuery.PlatformId != null)
                    {
                        companyinfo.PlatformId = (Guid)updateCompanyInfoQuery.PlatformId;
                    }
                    if (!string.IsNullOrEmpty(updateCompanyInfoQuery.OrganizationCode))
                    {
                        companyinfo.OrganizationCode = updateCompanyInfoQuery.OrganizationCode;
                    }
                    if (!string.IsNullOrEmpty(updateCompanyInfoQuery.BusinessLicensePhoto))
                    {
                        companyinfo.BusinessLicensePhoto = updateCompanyInfoQuery.BusinessLicensePhoto;
                    }
                    if (updateCompanyInfoQuery.AuthorizeBeginTime != null)
                    {
                        companyinfo.AuthorizeBeginTime = (DateTime)updateCompanyInfoQuery.AuthorizeBeginTime;
                    }
                    if (updateCompanyInfoQuery.AuthorizeEndTIme != null)
                    {
                        companyinfo.AuthorizeEndTIme = (DateTime)updateCompanyInfoQuery.AuthorizeEndTIme;
                    }
                    if (updateCompanyInfoQuery.ClientAuthorizationCodeNumber != null)
                    {
                        companyinfo.ClientAuthorizationCodeNumber = (int)updateCompanyInfoQuery.ClientAuthorizationCodeNumber;
                    }
                    if (!string.IsNullOrEmpty(updateCompanyInfoQuery.UsageTime))
                    {
                        companyinfo.UsageTime = updateCompanyInfoQuery.UsageTime;
                    }
                    if (updateCompanyInfoQuery.ContactsUserId != null)
                    {
                        companyinfo.ContactsUserId = (Guid)updateCompanyInfoQuery.ContactsUserId;
                    }
                    await _companyinfoRepository.UpdateAsync(companyinfo);
                    baseResultDto.IsSuccess = true;
                    baseResultDto.Code = HttpResultCode.Success;
                    baseResultDto.Message = "更新成功！";
                }
                else
                {
                    baseResultDto.IsSuccess = false;
                    baseResultDto.Code = HttpResultCode.SqlError;
                    baseResultDto.Message = "未查询到相关Id信息";
                }
            }
            catch (Exception e)
            {
                baseResultDto.IsSuccess = false;
                baseResultDto.Code = HttpResultCode.Error;
                baseResultDto.Message = e.Message.ToString();
            }
            return baseResultDto;
        }

        /// <summary>
        /// 更新审核信息
        /// </summary>
        /// <param name="approvalCompanyInfoQuery"></param>
        /// <returns></returns>
        public async Task<BaseResultDto> ApprovalCompanyInfo(ApprovalCompanyInfoQuery approvalCompanyInfoQuery)
        {
            BaseResultDto basePage = new BaseResultDto();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);
                List<CompanyInfo> companyinfolist = await _companyinfoRepository.GetAllListAsync(c => approvalCompanyInfoQuery.Ids.Contains(c.Id));

                companyinfolist.ForEach(info =>
                {
                    info.AuthorizeStates = approvalCompanyInfoQuery.AuthorizeStates;
                    info.UpdateUserId = token.Id;
                    info.UpdateTime = DateTime.Now;
                    _companyinfoRepository.UpdateAsync(info);
                });

                basePage.Code = HttpResultCode.Success;
            }
            catch (Exception e)
            {
                basePage.Code = HttpResultCode.Error;
                basePage.Message = e.Message.ToString();
            }
            return basePage;
        }

        ///// <summary>
        ///// 获取信息List
        ///// </summary>
        ///// <param name="Query"></param>
        ///// <returns></returns>
        //public async Task<PagePagingDto<GetCompanyInfoDto>> GetCompanyInfoListPage(GetCompanyInfoPageQuery Query)
        //{
        //    PagePagingDto<GetCompanyInfoDto> resultListDto = new PagePagingDto<GetCompanyInfoDto>();
        //    resultListDto.Code = HttpResultCode.SqlError;
        //    try
        //    {
        //        List<CompanyInfo> companyinfolist = await _companyinfoRepository.GetAllListAsync();
        //        if (companyinfolist != null && companyinfolist.Count > 0)
        //        {
        //            resultListDto.Code = HttpResultCode.Success;
        //            resultListDto.TotalCount = companyinfolist.Count;
        //            companyinfolist = companyinfolist.Skip((Query.PageIndex - 1) * Query.PageSize).Take(Query.PageSize).ToList();
        //            resultListDto.Data = ObjectMapper.Map<List<GetCompanyInfoDto>>(companyinfolist);
        //        }
        //    }
        //    catch (Exception e)
        //    {
        //        resultListDto.Code = HttpResultCode.Error;
        //        resultListDto.Message = e.Message.ToString();
        //    }
        //    return resultListDto;
        //}

        /// <summary>
        /// 获取客户名称集合
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<GetCompanyNameListDto>> GetCompanyNameList()
        {
            ResultListDto<GetCompanyNameListDto> resultListDto = new ResultListDto<GetCompanyNameListDto>();
            try
            {
                var token = UldAdminSessionContext.GetCurrentUserInfo(this._context);
                //先判断用户属于平台还是商户，商户只能选自己，平台能看所有商户
                if (token.CompanyId != null)
                {
                    //有商户id说明属于商户
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = ObjectMapper.Map<List<GetCompanyNameListDto>>(await _companyinfoRepository.GetAllListAsync(info => info.Id == token.CompanyId));
                    resultListDto.Count = resultListDto.Data.Count;
                }
                else
                {
                    //没有商户id说明属于平台
                    resultListDto.IsSuccess = true;
                    resultListDto.Code = HttpResultCode.Success;
                    resultListDto.Message = "查询成功！";
                    resultListDto.Data = ObjectMapper.Map<List<GetCompanyNameListDto>>(await _companyinfoRepository.GetAllListAsync(info => info.States == true && info.IsDeleted == false));
                    resultListDto.Count = resultListDto.Data.Count;
                }
                return resultListDto;
            }
            catch (Exception ex)
            {
                resultListDto.IsSuccess = false;
                resultListDto.Code = HttpResultCode.Error;
                resultListDto.Message = ex.Message.ToString();
            }
            return resultListDto;
        }
    }
}
